package cn.study.aviplayer;

import androidx.appcompat.app.AppCompatActivity;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.os.Bundle;

import java.util.concurrent.atomic.AtomicBoolean;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/**
 * opengl
 */
public class OpenGLPlayerActivity extends AbstractPlayerActivity {

    private final AtomicBoolean isPlaying = new AtomicBoolean();
    private long instance;
    private GLSurfaceView glSurfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_open_g_l_player);

        glSurfaceView = findViewById(R.id.glSurfaceView);

        glSurfaceView.setEGLContextClientVersion(2);
        glSurfaceView.setRenderer(renderer);
        //请求时渲染帧
        glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    }

    @Override
    protected void onStart() {
        super.onStart();
        instance = init(avi);
    }


    @Override
    protected void onResume() {
        super.onResume();

        glSurfaceView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();

        glSurfaceView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();

        free(instance);
    }


    private final Runnable player = new Runnable() {
        @Override
        public void run() {

            long frameDelay = (long) (1000 / getFrameRate(avi));

            while (isPlaying.get()) {

                glSurfaceView.requestRender();

                try {

                    Thread.sleep(frameDelay);
                } catch (InterruptedException e) {

                    break;
                }
            }
        }
    };


    private final GLSurfaceView.Renderer renderer = new GLSurfaceView.Renderer() {
        @Override
        public void onSurfaceCreated(GL10 gl, EGLConfig config) {

            initSurface(instance, avi);
            isPlaying.set(true);
            new Thread(player).start();
        }

        @Override
        public void onSurfaceChanged(GL10 gl, int width, int height) {


        }

        @Override
        public void onDrawFrame(GL10 gl) {

            if (!render(instance, avi)) {

                isPlaying.set(false);
            }
        }
    };


    /**
     * 初始化渲染器
     *
     * @param avi
     * @return
     */
    private native static long init(long avi);


    /**
     * 初始化opengl surface
     *
     * @param instance
     * @param avi
     */
    private native static void initSurface(long instance, long avi);

    /**
     * 用给定文件读取帧渲染
     *
     * @param instance
     * @param avi
     * @return
     */
    private native static boolean render(long instance, long avi);


    /**
     * 释放原生渲染器
     *
     * @param instance
     */
    private native static void free(long instance);

}
